#!/bin/bash

set_sshnopwd()
{
  echo_start "$1 ... ..."
  # 配置SSH免密。以下代码会导致因反复安装，SSHKEYS被反复生成和添加
  confirm_operate "init ssh"
  if [ $? -eq 0 ]; then
    cd ~
    # 存在id_rsa.pub，则提示是否重新生成
    if [ -f ~/.ssh/id_rsa.pub ]; then
      confirm_operate "id_rsa.pub has already existed, regenerate it ?" "n"
      if [ $? -eq 0 ]; then
        echo_trace "delete id_rsa*"
        rm -f /root/.ssh/id_rsa* || { die "rm id_rsa fail."; }
      fi
    fi
    local isGenKey="false"
    if [ ! -f ~/.ssh/id_rsa.pub ]; then
      echo_trace "DO ssh-keygen"
      ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa >> $SETUP_LOGFILE 2>&1 || { die "ssh-keygen fail."; }
      cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys || { die "cat id_rsa fail."; }
      chmod 600 ~/.ssh/authorized_keys || { die "chmod fail."; }
      isGenKey="true"
    fi
    cd - > /dev/null 2>&1 || { die "return install dir fail"; }
    local value_arr=($HYREN_ALLHOSTS)
    for i in ${value_arr[@]}; do
      # 如果本机在ALLHOSTS中，则跳过
      echo
      if [ "${i}" == "$LOCAL_HOSTNAME" ]; then echo_warn "skip ${i}"; continue; fi
      if [ "$isGenKey" = "false" ]; then
        # 如果上面生成了新的公钥，那么这里就不需要再去检查远程主机了
        ssh -o StrictHostKeyChecking=no $i "ls -l ~ >/dev/null" && { echo_info "set nopasswd login ... ... SKIP [${i}]"; continue; }
      fi
      echo_info "set nopasswd login =========>>>>>>>> START [${i}]"
      expect <<EOF
set timeout -1
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@${i}
expect {
"*(yes/no)*" {send  "yes\r";exp_continue}
"*assword:*" {send  "${ROOT_PASSWD}\r";exp_continue}
eof        {exit 0}}
EOF
      if [ $? -ne 0 ]; then
        die "set nopasswd login =========>>>>>>>> FAIL  [${i}]"
      else
        echo_info "set nopasswd login =========>>>>>>>> DONE  [${i}]"
      fi
    done
    #echo_success "$1"
    echo_passed "$1 done."
  else
    echo_passed "$1 SKIP"
  fi
}